import React, { Component } from 'react';
import { observable, action } from 'mobx';
import {ListView,SwipeAction,Tools} from 'weaver-mobile';
import { SearchAdvanced, ListViewPage } from 'weaver-mobile-page';
import showTemplates from '../../components/addressBook/showTemplates/index';
import * as api from '../../apis/addressBook';
import BaseStore from '../BaseStore';
import { GroupStore } from '../group/index';
const getLabel = Tools.getLabel;

const cmd = ['newly', 'underling', 'branch', 'v2resourcetree', 'v2grouptree', 'getResourceListByLetter', 'search'];
const conditionUrl = '/api/public/browser/condition/1'

class AddressBookStore extends BaseStore{
    rowKey = 'id';
    nameKey = 'lastname';
    currentPage = 1; 
    pageSize = 20;
    count = 0;
    dataTemp = {};

    @observable condition = '';
    @observable initialPage = 0;
    //虚拟维度
    @observable companyId = 1;
    @observable virtualDatas = [];
    //高级搜索store
    @observable advanceSearchPageStore =  new SearchAdvanced.Store({ route: '/addressBook', id: 'adjvanceSearch' });
    @observable listViewStore = new ListViewPage.Store();

    @observable refreshing = false;
    @observable condition = '';

    //pagination
    @observable listDatas = [];
    @observable count = 0;
    @observable treeData = [];
    @observable allResouceDataSource = null;

    @observable showPop = false;
    @observable alllevel = true;
    //是否有编辑公共组的权限
    @observable isHas = false
    @observable groupStore = new GroupStore();

    @observable searchvalue = "";
    @observable isNoAccount = true;

    cleanData = () => {
        this.showPop = false;
        this.companyId = 1;
        this.currentPage = 1;
        this.listDatas.length = 0;
        this.treeData.length = 0;
        this.dataTemp = {};
    }

    getConditionParams = () => {
        const {form: {formParams}} = this.advanceSearchPageStore;
        const {virtualtype} = formParams;
        if(virtualtype == null){
            this.companyId = 1;
        }else if(virtualtype != '')
            this.companyId = Number(virtualtype);
        return formParams;
    }

    getQueryParams = () => {
        let params = {cmd: cmd[this.initialPage], ...this.getConditionParams()};
        if(this.initialPage == 5) {
            params.letter = String.fromCharCode((this.currentPage - 1) + 65);
        }else if(this.initialPage < 3 || this.initialPage == 6){
            params.min = (this.currentPage - 1) * this.pageSize + 1;
            params.max = this.currentPage * this.pageSize;
            
            if(this.initialPage == 2 && this.alllevel){
                params.alllevel = 1;
            }
        }
        if(this.isNoAccount)
                params.isNoAccount = 1;
        if(this.initialPage == 0)
            params.virtualtype = '';
        return params;
    }

    @action init = (refresh = false) => {
        this.alllevel = true;
        this.isNoAccount = true;
        this.querySearchCondition();
        this.queryVirtual();
    }

    @action querySearchCondition = () => {
        this.advanceSearchPageStore.getData({
            url: conditionUrl
        }).then(form => {
            this.setActiveTab(this.initialPage);
        });
    }

    @action queryVirtual = () => {
        api.queryVirtual({cmd: 'companyvirtual'}).then(data => {
            const datas = data.datas || [];
            const virtualDatas = [];
            datas.forEach((v) => {
              virtualDatas.push({
                ...v,
                label: v.virtualtype,
                value: v.id,
              });
            });
            this.virtualDatas = virtualDatas;
            this.companyId = datas.length > 0 ? virtualDatas[0].value : '';
        }, error => {});
    }

    @action doSearch = () => {
        this.currentPage = 1;
        this.cleanData();
        this.queryData(this.getQueryParams());
    }

    @action doReset = () => {
        const {form} = this.advanceSearchPageStore;
        form.resetFields();
    }

    @action clearHistory = (id) => {
        const p = {isDelete: 1};
        if(id != null)
            Object.assign(p, {resourceid: id});
        this.cleanData();
        this.queryData({...this.getQueryParams(), ...p}, () => this.queryData(this.getQueryParams()));
    }

    @action setActiveTab = index => {
        this.initialPage = index;
        this.alllevel = true;
        this.doReset();
        this.cleanData();
       
        //是否有编辑公共组的权限
        if (index == 4) {
            this.groupStore.getAdviceInfo().then( () => {
                const { isHas } = this.groupStore;
                this.isHas = isHas;
                const params  = this.getQueryParams();
                if (this.pageType == "group") {
                    Object.assign(params,{
                        showNum: 1
                    });
                }
                this.queryData(params);
            } );
        }else{
             this.queryData(this.getQueryParams());
        }
    }

    @action onVirtualChangeHandle = v => {
        this.companyId = v;
        const {form} = this.advanceSearchPageStore;
        form.updateField('virtualtype', v== 0 ? '' : v.toString());
        this.doSearch();
    }

    @action onQuickSearchChangeHandle = v => {
        const {form} = this.advanceSearchPageStore;
        form.updateField('lastname', v.toString());
    }

    @action refreshData = () => {
        this.listDatas.length = 0;
        this.treeData.length = 0;
        this.dataTemp = {};
        this.setCurrentPage(1);
    }

    @action setCurrentPage = idx => {
        if(idx == null)
            this.currentPage++;
        else if(idx === this.currentPage && this.currentPage != 1){
            this.listViewStore.setState({hasMore: false, loading: false});
            return;
         } else{
            this.cleanData();
            this.currentPage = idx;
         }
        this.queryData(this.getQueryParams());
    }

    @action doQuickSearch = () => {
        this.initialPage = 6;
        this.cleanData();
        this.queryData(this.getQueryParams());
    }

    @action onClearSearchCondition = () => {
        this.onQuickSearchChangeHandle('');
        this.doQuickSearch();
    }

    @action queryData = (params, callback) => {
        [3, 4, 6].indexOf(this.initialPage) < 0 && this.listViewStore.setState({loading: true});
        api.queryData(params).then(data => {
            if(callback){
                callback();
                return;
            }
            const { datas } = data;
            switch(this.initialPage){
                case 3: 
                    this.setTreeData(datas);
                    break;
                case 4: 
                    this.setGroupTreeData(datas);
                    break;
                case 5:
                    this.dataTemp[params.letter] = datas;
                    this.updateDataSourceWhenSelected();
                    this.setListData(data);
                    break;
                default:
                    if(Array.isArray(datas)){
                        this.setListData(data);
                    }
                    break;
            }
        }, error => {});
    }

    @action updateDataSourceWhenSelected = () => {
        const getSectionData = (dataBlob, sectionID) => dataBlob[sectionID];
        const getRowData = (dataBlob, sectionID, rowID) => dataBlob[rowID];

        this.allResouceDataSource = new ListView.DataSource({
            getRowData,
            getSectionHeaderData: getSectionData,
            rowHasChanged: (row1, row2) => row1 !== row2,
            sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
        });
        this.genData(this.allResouceDataSource, this.dataTemp);
    }

    @action genData = (ds, provinceData) => {
        const dataBlob = {};
        const sectionIDs = [];
        const rowIDs = [];
        const rowKey = this.rowKey;
        for (let i = 0; i < 26; i += 1) {
            const letter = String.fromCharCode(65 + i);
            sectionIDs.push(letter);
            rowIDs.push([letter]);
            dataBlob[letter] = letter;
        }
        Object.keys(provinceData).forEach((item) => {
            const itemIndex = item.charCodeAt() - 65;
            dataBlob[item] = item;
            rowIDs[itemIndex] = [];
            provinceData[item].forEach((v) => {
                rowIDs[itemIndex].push(v[rowKey]);
                dataBlob[v[rowKey]] = v;
            });
        });
        this.allResouceDataSource = ds.cloneWithRowsAndSections(dataBlob, sectionIDs, rowIDs);
    }

    @action setListData = data => {
        const { count, datas } = data;
        const { template } = showTemplates;
        this.count = data.count;
        this.listDatas = [...this.toJS(this.listDatas), ...datas];
        
        const dataSource = this.listViewStore.dataSource.cloneWithRows(this.toJS(this.listDatas));
        this.listViewStore.setState({
            nameKey: this.nameKey,
            rowKey: this.rowKey,
            data: this.listDatas,
            template: { template },
            dataSource,
            hasMore: datas.length > 0 && this.count >= this.pageSize,
            loading: false,
            isTable: false,
            getData: () => {}
        });
    }

    genNode = (d, lv, index) => {
        let {nodeid: key, id, lastname: name, type: nodeType, pid, isParent, icon} = d;
        let haschild = (isParent || isParent === 'true');
        icon = icon || '';
        switch(nodeType){
            case 'subcom':
                icon = 'blog-homepage-o';
                break;
            case 'dept':
                icon = 'branch';
                break;
            case 'group':
                icon = 'gonggongzu';
                if(id < -1){
                    haschild = true;
                }
                break;
        }
        const data =  {
            ...d,
            key,
            id,
            name,
            nodeType,
            pid,
            haschild,
            childs: [],
            checkable: false,
            icon,
            lv
        }

        if (nodeType === "group") {
            Object.assign(data,{
                name: (
                    <SwipeAction
                      autoClose
                      right={ ( (index == 0 && this.isHas) || (index == 1) ) ? [
                        {
                          text: getLabel(93, "编辑"),
                          onPress: (e) => {
                            e.stopPropagation();
                            this.operateGroup( (data.pid == "-2") ? "1" : "0", id) ;
                          },
                          className:"brand-btn",
                          style: { color: 'white',padding: "0 10px" },
                        },
                        {
                          text: getLabel(91, '删除'),
                          onPress: (e) => {
                            e.stopPropagation();

                            const {
                                renderDeleteConform,
                                deleteGroup
                            } = this.groupStore;

                            //确认框 -> 删除 -> 刷新树
                            renderDeleteConform(() => {
                                deleteGroup(id).then(() => {
                                    this.queryData(this.getQueryParams());
                                })
                            });
                            
                          },
                          style: { backgroundColor: '#F4333C', color: 'white',padding: "0 10px" },
                        },
                      ] : [{
                          text: getLabel('519503','提交调整建议') ,
                          onPress: (e) =>{
                            e.stopPropagation();
                            this.adviceGroup(id);
                          } ,
                          className:"brand-btn",
                          style: { color: 'white' },
                        }]
                    }
                    >
                        <span dangerouslySetInnerHTML = {{ __html: name.replace(/\([^\)]*\)/g, match => `<span class="group-num">${match}</span>`)}}></span>
                    </SwipeAction>
                )
            })
        }

        return data;
    }

    //type区分公共组还是私人组
    //id为常用组id
    operateGroup = (type, id) => {
       if (window.em && window.em.checkJsApi('openLink')) {
            let url = `/spa/hrm/static4mobile/index.html#/groupOp?type=${type}`;
            //编辑常用组
            if (id) {
                url = `${url}&id=${id}`
            }
            window.em.openLink({
                url,
                openType: 2,
                sysId: window.localStorage.emobile_ec_id
            });
        }
    }

    adviceGroup = (id) => {
        if (window.em && window.em.checkJsApi('openLink')) {
            window.em.openLink({
                url: `/spa/hrm/static4mobile/index.html#/groupAdvice?targetId=${id}`,
                openType: 2,
                sysId: window.localStorage.emobile_ec_id
            });
        }
    }

    @action setTreeData = datas => {
        const { children = [] } = datas;
        const treeData = [];
        children.map(d => {
            treeData.push(this.genNode(d, 1));
        })
        this.treeData = [treeData];
    }

    @action setGroupTreeData = datas => {
        const { children = [] } = datas;
        const groups = [];
        children.map((g, i) => {
            const group = {
                key: i,
                id: g.id,
                icon: g.icon,
                name: g.lastname,
                open: g.open || g.open === 'true',
                type: g.type
            };
            const {children = []} = g;
            const treeData = [];
            children.map(d => {
                treeData.push(this.genNode(d, 1, i));
            })
            Object.assign(group, {treeData});
            groups.push(group);
        })
        this.treeData = groups;
    }

    @action asyncOrgChildNode = node => {
        return new Promise(resolve => {
            if(node.haschild && node.nodeType != 'resource'){
                const {form: {formParams}} = this.advanceSearchPageStore;
                const {virtualtype} = formParams;
                const params = {
                    cmd: cmd[this.initialPage],
                    type: node.nodeType,
                    id: node.id,
                    virtualtype,
                }
                this.isNoAccount && Object.assign(params, {isNoAccount: 1});
                api.queryData(params).then(data => {
                    const { datas = [] } = data;
                    const res = datas.map(d => this.genNode(d, node.lv + 1));
                    resolve(res);
                })
            }
        })
    }

    @action asyncGroupChildNode = node => {
        return new Promise(resolve => {
            if(node.haschild && node.nodeType != 'resource'){
                const params = {
                    cmd: cmd[this.initialPage],
                    type: 'group',
                    id: node.id
                }
                this.isNoAccount && Object.assign(params, {isNoAccount: 1});
                api.queryData(params).then(data => {
                    const { datas = [] } = data;
                    const res = datas.map(d => this.genNode(d, node.lv + 1));
                    resolve(res);
                })
            }
        })
    }

    @action setShowPop = bool => this.showPop = bool;

    @action onPopoverSelectHandle = node => {
        if(node.key == 'isNoAccount')
            this.isNoAccount = !this.isNoAccount;
        if(node.key == 'alllevel')
            this.alllevel = !this.alllevel;
        this.setCurrentPage(1);
        this.showPop = false;
    }

    setPageType = (type) => {
        this.pageType = type;
    }

    @action handleSearchChange = (value) => {
        this.searchvalue = value;
    }

    handleSearchSubmit = () => {
        const params = {
            cmd:"v2grouptree",
            groupName: this.searchvalue,
            pageSize:10,
            current:1,
            min:1,
            max:10,
            virtualtype:1,
            status:8
        }
        this.queryData(params);
    }
}

export const addressBookStore = new AddressBookStore();